package calao;

import java.util.HashMap;
import java.util.Vector;

import calao.storage.Field;
import calao.storage.Record;
import calao.storage.Table;
import calao.util.Bits;

public class Membership 
{
	
	public final static int INACTIVE_FLAG = 1;
	
	static final Table TABLE = new Table("calao.Member"); 

	static final Field<Integer> WORKSPACE_ID = 
		TABLE.createField("wsid", Field.INTEGER);	

	static final Field<Long> GLOBAL_USER_ID = 
		TABLE.createField("guid", Field.LONG);	

	static final Field<String> NAME = 
		TABLE.createField("name", Field.STRING);	

	static final Field<Integer> PROFILES = 
		TABLE.createField("profile", Field.INTEGER, true);	

	static final Field<Integer> FLAGS = 
		TABLE.createField("flags", Field.INTEGER);	

	static final Field<HashMap<String,String>> PROPERTIES = 
		TABLE.createField("properties", new HashMap<String,String>());	

	static {
		TABLE.createPrimaryKeyIndex(WORKSPACE_ID, GLOBAL_USER_ID);
		TABLE.createIndex(GLOBAL_USER_ID);
	}
	
	final Server server;
	final int wsid;
	final long guid;
	String name;
	int[] profiles;
	int flags;
	final HashMap<String,String> properties;
	
	Membership(Workspace ws, long guid, String name, int[] profiles, int flags,
			HashMap<String,String> properties)
	{
		this.server = ws.server;
		this.wsid = ws.id;
		this.guid = guid;
		this.name = name;
		this.profiles = profiles;
		this.properties = properties!=null? properties : new HashMap<String,String>();
		this.flags = flags;
	}

	Membership(Workspace ws, Record record) 
	{
		this(ws, record.get(GLOBAL_USER_ID), record.get(NAME), record.getAllInt(PROFILES),
				record.getInt(FLAGS), record.get(PROPERTIES));
	}	
	
	public void setProperty(String name, String value)
	{
		properties.put(name, value);
	}

	public long getGlobalUserId() {
		return guid;
	}

	public String getName() 
	{
		return name;
	}

	public int[] getProfileIds() 
	{
		return profiles;
	}
	
	public Profile[] getProfiles() 
	{
		Vector<Profile> result = new Vector<Profile>();
		ProfileManager profileMgr = getWorkspace().getProfileManager();
		for (int profileId : profiles) {
			Profile profile = profileMgr.getProfile(profileId);
			if (profile!=null) result.add(profile);
		}
		return result.toArray(new Profile[result.size()]);
	}

	public void save()
	{
		getWorkspace().getMembershipManager().save(this);
	}
	
	public Workspace getWorkspace()
	{
		return server.getWorkspace(wsid);
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setProfiles(int[] profiles) {
		this.profiles = profiles;
	}

	public boolean isInactive() {
		return Bits.hasBits(flags, INACTIVE_FLAG);
	}

	public void setInactive(boolean state) {
		if (state) flags = Bits.setBits(flags, INACTIVE_FLAG);
		else flags = Bits.clearBits(flags, INACTIVE_FLAG);
	}

}
